package com.amkai.aes.webservice.binary.objecthandler.inventory;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.exceptions.inventory.AdjustmentManagerException;
import com.amkai.aes.aescommon.exceptions.inventory.OpenInventoryException;
import com.amkai.aes.aescommon.factory.RADBeanFactory;
import com.amkai.aes.aescommon.inventory.InventorySearchParam;
import com.amkai.aes.aescommon.inventory.OneToOneHelper;
import com.amkai.aes.aescommon.inventory.ReceiveOrderParam;
import com.amkai.aes.aescommon.service.binary.job.inventory.AdjustmentHistoryInfo;
import com.amkai.aes.aescommon.service.binary.job.inventory.InventoryElementHistoryInfo;
import com.amkai.aes.aescommon.service.binary.job.inventory.InventoryJob;
import com.amkai.aes.aescommon.service.binary.job.inventory.InventoryJobKind;
import com.amkai.aes.aescommon.service.binary.job.inventory.InventoryJobResult;
import com.amkai.aes.aescommon.service.binary.job.inventory.InventorySearchKind;
import com.amkai.aes.generatedbeans.cdmcasehistory.SupplyUsageKind;
import com.amkai.aes.generatedbeans.cdmcasehistory.logdetails.resources.AdjustmentDescriptor;
import com.amkai.aes.generatedbeans.cdmcasehistory.logdetails.resources.TransactionDescriptor;
import com.amkai.aes.generatedbeans.cdmcasehistory.logdetails.resources.TransferDescriptor;
import com.amkai.aes.generatedbeans.common.Address;
import com.amkai.aes.generatedbeans.common.OrganizationContact;
import com.amkai.aes.generatedbeans.dictionary.Item;
import com.amkai.aes.generatedbeans.inventory.BilledByType;
import com.amkai.aes.generatedbeans.inventory.InventoryElement;
import com.amkai.aes.generatedbeans.inventory.InventorySetupOptions;
import com.amkai.aes.generatedbeans.inventory.ItemLocation;
import com.amkai.aes.generatedbeans.inventory.SerialNumber;
import com.amkai.aes.generatedbeans.inventory.ServiceHistory;
import com.amkai.aes.generatedbeans.inventory.ServiceWarriantyInformation;
import com.amkai.aes.generatedbeans.inventory.TransactionCalculationEffect;
import com.amkai.aes.generatedbeans.inventory.VendorOrderInformation;
import com.amkai.aes.generatedbeans.inventory.depletion.TransactionLog;
import com.amkai.aes.generatedbeans.inventory.items.SupplyResourceItem;
import com.amkai.aes.generatedbeans.inventory.items.SupplyResourceLocation;
import com.amkai.aes.generatedbeans.inventory.purchasing.PurchaseOrder;
import com.amkai.aes.generatedbeans.inventory.purchasing.PurchaseOrderLine;
import com.amkai.aes.generatedbeans.inventory.purchasing.ReceiveOrder;
import com.amkai.aes.generatedbeans.inventory.purchasing.ReceiveOrderLine;
import com.amkai.aes.generatedbeans.inventory.requisitioning.OrderRequisition;
import com.amkai.aes.generatedbeans.inventory.requisitioning.OrderRequisitionLine;
import com.amkai.aes.generatedbeans.inventory.stock.Adjustment;
import com.amkai.aes.generatedbeans.inventory.stock.Stock;
import com.amkai.aes.generatedbeans.inventory.stock.StockAdjustment;
import com.amkai.aes.generatedbeans.inventory.stock.StockOnLocation;
import com.amkai.aes.generatedbeans.inventory.stock.StockOnLocationAdjustment;
import com.amkai.aes.generatedbeans.organization.Department;
import com.amkai.aes.generatedbeans.pmcase.PmCase;
import com.amkai.aes.generatedbeans.procedure.CarrierCodes;
import com.amkai.aes.server.dictionary.DictionarySchedulingResourceManager;
import com.amkai.aes.server.dictionary.ServerContractManager;
import com.amkai.aes.server.dictionary.SharedDictionaryManager;
import com.amkai.aes.server.inventory.managers.AdjustmentManager2;
import com.amkai.aes.server.inventory.managers.InventorySearcher;
import com.amkai.aes.server.inventory.managers.InventorySetupManager;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.rad.designerbase.beans.ChangedKind;

public class InventoryJobHandler implements JobObjectHandler<InventoryJob, Serializable, InventoryJobResult> {
	private static final Log log = LogFactory.getLog(InventoryJobHandler.class);

	public InventoryJobResult downloadInventorySetup(InventoryJob job) throws Exception {
		InventoryJobResult result = new InventoryJobResult();

		if (job.getSearchParam() != null) {
			SessionManager sm = SiteManager.Start();
			sm.openSession();
			try {
				Query query = sm.execute("FROM InventorySetupOptions AS option WHERE option.baseOrganization.id = :baseOrganization");
				query.setParameter("baseOrganization", job.getSearchParam().getBaseOrganizationId());

				InventorySetupOptions option = (InventorySetupOptions) query.uniqueResult();
				fetchInventorySetupOptions(option);
				result.setInventorySetupOptions(option);
			} finally {
				sm.closeSession();
			}
		}

		return result;
	}

	private void fetchInventorySetupOptions(InventorySetupOptions option) {
		if (option != null) {
			if (option.getApprovalBy() != null) {
				option.getApprovalBy().getName();
				option.getApprovalBy().getPerson().getDisplayName();

			}
			if (option.getBaseOrganization() != null) {
				option.getBaseOrganization().getName();
			}
			if (option.getPurchaseOrderCreationCalculation() != null) {
				option.getPurchaseOrderCreationCalculation().getFrom();
				if (option.getPurchaseOrderCreationCalculation().getAverageCalculationKind() != null) {
					option.getPurchaseOrderCreationCalculation().getAverageCalculationKind().name();
				}
				if (option.getPurchaseOrderCreationCalculation().getCreationKind() != null) {
					option.getPurchaseOrderCreationCalculation().getCreationKind().name();
				}
			}
			if (option.getTaskBackOrderPassport() != null) {
				option.getTaskBackOrderPassport().getName();
				option.getTaskBackOrderPassport().getPerson().getDisplayName();
			}
			if (option.getTaskSupplyLevelDropPassport() != null) {
				option.getTaskSupplyLevelDropPassport().getName();
				option.getTaskSupplyLevelDropPassport().getPerson().getDisplayName();
			}

			if (option.getPurchaseOrderCreationCalculation() != null){
				option.getPurchaseOrderCreationCalculation().getNumberOfDays();
			}
				
			
			fetchItem(option.getBackToStockFromCDM());
			fetchItem(option.getDefectAdd());
			fetchItem(option.getDefectDeplete());
			fetchItem(option.getDepleteFromCDM());
			fetchItem(option.getExpirationReached());
			fetchItem(option.getManualAdjustmentAdd());
			fetchItem(option.getManualAdjustmentDeplete());
			fetchItem(option.getReceivingCode());
			fetchItem(option.getReturnToVendor());
			fetchItem(option.getPhyInvAdd());
			fetchItem(option.getPhysInvDepletion());
			fetchItem(option.getTaskBackOrderWorkGroup());
			fetchItem(option.getTaskSupplyLevelDropWorkgroup());
			fetchItem(option.getTransfer());
			fetchItem(option.getWastedRemovedInCDM());
			fetchItem(option.getWatedItemReturned());
			fetchItem(option.getDefaultLocation());
		}
	}

	private void fetchItem(Item item) {
		if (item != null) {
			item.getName();
		}
	}

	@Override
	public InventoryJobResult process(InventoryJob job, Serializable object) throws Exception {
		log.debug("InventoryJobKind: " + job.getKind());

		switch (job.getKind()) {
		case DOWNLOAD_INVENTORY_SETUP:
			return downloadInventorySetup(job);

		case PROCESS_ADJUSTMENTS:
			return processAdjustments(job);

		case SEARCH:
			return search(job.getSearchParam());

		case UPLOAD_INVENTORY_SETUP:
			return uploadInventorySetup(job.getInventorySetupOptions());

		case UPLOAD_SUPPLY:
			return uploadSupplyResourceItem(job);

		case SEARCH_ORDERED_ITEMS:
			return getOrderedItems(job);

		case ORDERREQUISITIONLINES:
			return getRequisitionLines(job);

		case ORDERREQUISITIONBYID:
			return getRequisitionById(job);

		case UPLOAD_ITEMLOCATION:
			return uploadItemLocation(job);

		case DOWNLOAD_RECEIVEORDER_LINES:
			return DownloadReceiveOrderLines(job, null);
		case DOWNLOAD_PURCHASEORDER:
			return DownloadPO(job);
		case ADJUSTMENT_HISTORY_INFO:
			return getAdjustmentHistoryInfo(job);
		}

		return null;
	}

	private InventoryJobResult DownloadPO(InventoryJob job) throws Exception {
		final String queryprefixisnull = "select po from PurchaseOrder po where po.poNumber = :ponum and po.prefix is NULL and po.baseOrganization.id = :depId";
		final String query = "select po from PurchaseOrder po where po.poNumber = :ponum and po.prefix = :prefx and po.baseOrganization.id = :depId";
		InventoryJobResult result = new InventoryJobResult();
		SessionManager sm = SiteManager.Start();
		sm.openSession();
		try {
			PurchaseOrder npo = new PurchaseOrder();
			Query q;
			if (job.getSearchParam().getPrefx() == null) {
				q = sm.execute(queryprefixisnull);
				q = q.setLong("ponum", job.getSearchParam().getPonum());
				q.setLong("depId", job.getModuleDepartment().getId());

			} else {
				q = sm.execute(query);
				q = q.setLong("ponum", job.getSearchParam().getPonum());

				q.setString("prefx", job.getSearchParam().getPrefx());
				q.setLong("depId", job.getModuleDepartment().getId());

			}

			npo = (PurchaseOrder) q.uniqueResult();
			if (npo != null) {
				npo.getId();
				npo.getBaseOrganization().getId();
				npo.getBaseOrganization().getName();
				// KKORNEL: AES-12515
				if (npo.getBaseOrganization().getParent() != null) {
					npo.getBaseOrganization().getParent().getId();
					npo.getBaseOrganization().getParent().getKind();
					npo.getBaseOrganization().getParent().getName();
				}
				if (npo.getReceiveOrders() != null) {
					for (ReceiveOrder ro : npo.getReceiveOrders()) {
						ro.getId();
						ro.getSalesTaxAmount();
						ro.getShippingCost();
						ro.getShippingNumber();
					}
				}
				if (npo.getPatient() != null)
					if (npo.getPatient().getPerson() != null)
						npo.getPatient().getPerson().getDisplayName();
				if (npo.getCreatedBy() != null) {
					npo.getCreatedBy().getName();
					if (npo.getCreatedBy().getPerson() != null)
						npo.getCreatedBy().getPerson().getDisplayName();

				}
				if (npo.getApprovedBy() != null) {
					npo.getApprovedBy().getName();
					if (npo.getApprovedBy().getPerson() != null)
						npo.getApprovedBy().getPerson().getDisplayName();

				}

				if (npo.getVendor() != null) {
					npo.getVendor().getId();

					/*
					 * if (npo.getVendor().getOrganizationContacts() != null){
					 * for (OrganizationContact oc :
					 * npo.getVendor().getOrganizationContacts()){
					 * oc.getContactName(); oc.getMobilePhone(); oc.getEmail();
					 * oc.getComment(); oc.getFax(); oc.getHomePhone();
					 * oc.getWorkPhone(); } }
					 */

					if (npo.getVendor().getOrganizationGroup() != null) {
						if (npo.getVendor().getOrganizationGroup().getAddresses() != null) {
							for (Address ad : npo.getVendor().getOrganizationGroup().getAddresses()) {
								if (ad.getLocation() != null) {
									if (ad.getLocation().getPhone() != null) {
										ad.getLocation().getPhone().getNumber();
									}
									if (ad.getLocation().getFax() != null) {
										ad.getLocation().getFax().getNumber();
									}
									if (ad.getLocation().getAlterPhone() != null) {
										ad.getLocation().getAlterPhone().getNumber();
									}
									if (ad.getLocation().getZipCode() != null) {
										if (ad.getLocation().getZipCode().getCity() != null) {
											ad.getLocation().getZipCode().getCity().getName();
										}
										if (ad.getLocation().getZipCode().getZip() != null) {
											ad.getLocation().getZipCode().getZip().getName();

											if (ad.getLocation().getZipCode().getZip().getState() != null) {
												ad.getLocation().getZipCode().getZip().getState().getName();
											}
										}
									}
								}
							}

						}

					}
				}
				if (npo.getVendor().getOrganizationContacts() != null) {
					for (OrganizationContact oc : npo.getVendor().getOrganizationContacts()) {

						if (oc.getWorkPhone() != null)
							oc.getWorkPhone().getNumber();
						if (oc.getMobilePhone() != null)
							oc.getMobilePhone().getNumber();
						if (oc.getFax() != null)
							oc.getFax().getNumber();
						if (oc.getHomePhone() != null)
							oc.getHomePhone().getNumber();
						if (oc.getAlternatePhone() != null)
							oc.getAlternatePhone().getNumber();
						if (oc.getPager() != null)
							oc.getPager().getNumber();
					}
				}
				if (npo.getVendorContact() != null) {
					npo.getVendorContact().getId();
					if (npo.getVendorContact().getWorkPhone() != null)
						npo.getVendorContact().getWorkPhone().getNumber();
					if (npo.getVendorContact().getMobilePhone() != null)
						npo.getVendorContact().getMobilePhone().getNumber();
					if (npo.getVendorContact().getFax() != null)
						npo.getVendorContact().getFax().getNumber();

					npo.getVendorContact().getEmail();
					npo.getVendorContact().getComment();
					npo.getVendorContact().getContactName();
				}
				if (npo.getBillTo() != null) {
					if (npo.getBillTo().getLocation() != null) {
						if (npo.getBillTo().getLocation().getPhone() != null) {
							npo.getBillTo().getLocation().getPhone().getNumber();
						}
						if (npo.getBillTo().getLocation().getFax() != null) {
							npo.getBillTo().getLocation().getFax().getNumber();
						}
						if (npo.getBillTo().getLocation().getAlterPhone() != null) {
							npo.getBillTo().getLocation().getAlterPhone().getNumber();
						}
						if (npo.getBillTo().getLocation().getZipCode() != null) {
							if (npo.getBillTo().getLocation().getZipCode().getCity() != null) {
								npo.getBillTo().getLocation().getZipCode().getCity().getName();
							}
							if (npo.getBillTo().getLocation().getZipCode().getZip() != null) {
								npo.getBillTo().getLocation().getZipCode().getZip().getName();

								if (npo.getBillTo().getLocation().getZipCode().getZip().getState() != null) {
									npo.getBillTo().getLocation().getZipCode().getZip().getState().getName();
								}
							}
						}
					}
				}

				if (npo.getShipTo() != null) {
					if (npo.getShipTo().getLocation() != null) {
						if (npo.getShipTo().getLocation().getPhone() != null) {
							npo.getShipTo().getLocation().getPhone().getNumber();
						}
						if (npo.getShipTo().getLocation().getFax() != null) {
							npo.getShipTo().getLocation().getFax().getNumber();
						}
						if (npo.getShipTo().getLocation().getAlterPhone() != null) {
							npo.getShipTo().getLocation().getAlterPhone().getNumber();
						}
						if (npo.getShipTo().getLocation().getZipCode() != null) {
							if (npo.getShipTo().getLocation().getZipCode().getCity() != null) {
								npo.getShipTo().getLocation().getZipCode().getCity().getName();
							}
							if (npo.getShipTo().getLocation().getZipCode().getZip() != null) {
								npo.getShipTo().getLocation().getZipCode().getZip().getName();

								if (npo.getShipTo().getLocation().getZipCode().getZip().getState() != null) {
									npo.getShipTo().getLocation().getZipCode().getZip().getState().getName();
								}
							}
						}
					}
				}
				/*
				 * if (npo.getBillTo() != null){ npo.getBillTo().getId(); if
				 * (npo.getBillTo().getLocation() != null)
				 * npo.getBillTo().getLocation().getId(); } if (npo.getShipTo()
				 * != null) { npo.getShipTo().getId(); if
				 * (npo.getShipTo().getLocation() != null)
				 * npo.getShipTo().getLocation().getId(); }
				 */

				if (npo.getCreatedBy() != null) {
					if (npo.getCreatedBy().getPerson() != null) {
						npo.getCreatedBy().getPerson().getId();
						npo.getCreatedBy().getPerson().enableChangeLog();
						npo.getCreatedBy().getPerson().getDisplayName();
					}
				}

				if (npo.getCanceledBy() != null) {
					npo.getCanceledBy().getName();
					if (npo.getCanceledBy().getPerson() != null) {
						npo.getCanceledBy().getPerson().getId();
						npo.getCanceledBy().getPerson().getDisplayName();
					}
				}
				if (npo.getPmCase() != null) {
					npo.getPmCase().getName();
				}
				if (npo.getPatient() != null) {
					if (npo.getPatient().getCases() != null) {
						for (PmCase acase : npo.getPatient().getCases()) {
							acase.getName();
						}
					}
				}

				for (PurchaseOrderLine pol : npo.getPurchaseOrderLines()) {

					int h = pol.getReceiveOrderLines().size();
					InventoryJob j = new InventoryJob(InventoryJobKind.DOWNLOAD_RECEIVEORDER_LINES);
					j.setModuleDepartment(job.getModuleDepartment());
					// j.getModuleDepartment().setId(job.getModuleDepartment().getId());
					InventorySearchParam isp = new InventorySearchParam(null);
					isp.setPoLineId(pol.getId());
					j.setSearchParam(isp);
					pol.getReceiveOrderLines().addAll(DownloadReceiveOrderLines(j, sm).getReceiveOrderLines());
					j = null;
					isp = null;
					pol.getInventoryElement().getId();
					pol.getInventoryElement().getSupplyResourceItem().getName();
					pol.getInventoryElement().getSupplyResourceItem().getCategory().getName();

					if (pol.getInventoryElement().getSupplyResourceItem().getUsageUnit() != null)
						pol.getInventoryElement().getSupplyResourceItem().getUsageUnit().getName();

					if (pol.getSupplyResourceLocation() != null) {
						pol.getSupplyResourceLocation().getId();

						pol.getSupplyResourceLocation().getShortName();
					}
					pol.setPurchaseOrder(npo);
					if (pol.getReceiveOrderLines() != null)
						pol.getReceiveOrderLines().size();
					/*
					 * if (pol.getReceiveOrderLines() != null){
					 * 
					 * for(ReceiveOrderLine rol : pol.getReceiveOrderLines()){
					 * 
					 * if (rol.getAdjustment() != null){
					 * rol.getAdjustment().getId();
					 * rol.getAdjustment().getQuantity(); } } }
					 */
					/***/
					pol.getInventoryElement().getId();
					pol.getInventoryElement().getSupplyResourceItem().getName();
					if (pol.getInventoryElement().getSupplyResourceItem().getCategory() != null)
						pol.getInventoryElement().getSupplyResourceItem().getCategory().getName();
					if (pol.getSupplyResourceLocation() != null) {
						pol.getSupplyResourceLocation().getId();

						pol.getSupplyResourceLocation().getShortName();
					}
					pol.getPurchaseOrder().getId();
					pol.getPurchaseOrder().getPoNumber();
					if (pol.getVendorOrderInformation() != null) {
						pol.getVendorOrderInformation().getId();
						if (pol.getVendorOrderInformation().getVendor() != null) {
							pol.getVendorOrderInformation().getVendor().getId();
							pol.getVendorOrderInformation().getVendor().getDescription();
						}

						pol.getVendorOrderInformation().getPricePerOrderingUnit();
						if (pol.getVendorOrderInformation().getOrderingUnit() != null)
							pol.getVendorOrderInformation().getOrderingUnit().getName();
						pol.getVendorOrderInformation().getVendorDescription();
						pol.getVendorOrderInformation().getVendorCatalog();
						pol.getVendorOrderInformation().getManufacturerCatalog();
						pol.getVendorOrderInformation().getManufacturer().getDescription();

					}

					for (VendorOrderInformation vo : pol.getInventoryElement().getVendorOrderInformations()) {
						vo.getId();
					}

					if (pol.getInventoryElement().getItemLocations().size() > 0) {
						for (ItemLocation il : pol.getInventoryElement().getItemLocations()) {
							if (il != null) {
								il.getId();
								if (il.getLocation() != null) {
									il.getLocation().getName();
								}
							}

						}

					}
				}
			}
			result.setPurchaseOrders(new ArrayList<PurchaseOrder>());
			result.getPurchaseOrders().add(npo);
			return result;

		} catch (Exception e) {
			// logger.error("ImportCheckoutHandler: ", e);

			throw e;
		} finally {
			sm.closeSession();
		}

	}

	private InventoryJobResult DownloadReceiveOrderLines(InventoryJob job, SessionManager sm) throws Exception {
		final String query = "select roi from ReceiveOrderLine roi where roi.purchaseOrderLine.id = :polId and roi.purchaseOrderLine.purchaseOrder.baseOrganization.id = :depId order by roi.receiveOrder.receivedDate desc";
		SessionManager asm = sm;
		Boolean needtoclosesession = false;
		if (asm == null) {
			asm = SiteManager.Start();
			needtoclosesession = true;
		}
		try {
			if (needtoclosesession)
				asm = SiteManager.Start();
			InventoryJobResult result = new InventoryJobResult();
			if (needtoclosesession)
				asm.openSession();
			Query q = asm.execute(query);
			q = q.setLong("polId", job.getSearchParam().getPoLineId());
			q = q.setLong("depId", job.getModuleDepartment().getId());
			List<ReceiveOrderLine> req = q.list();
			if (req.size() > 0) {
				for (ReceiveOrderLine rol : req) {
					rol.getReceiveOrder().getReceivedDate();
					rol.getReceiveOrder().getShippingNumber(); // AES-10430
					rol.getAdjustment().getId();
					rol.getAdjustment().getQuantity();
				}
			}
			result.setReceiveOrderLines(req);
			return result;

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			throw (e1);
		} finally {
			if (needtoclosesession)
				asm.closeSession();
		}

	}

	private InventoryJobResult getRequisitionById(InventoryJob job) throws Exception {
		final String query = "select req from OrderRequisition req where req.id = :reqid";
		SessionManager sm = null;

		try {
			sm = SiteManager.Start();
			InventoryJobResult result = new InventoryJobResult();
			sm.openSession();
			Query q = sm.execute(query);
			q = q.setLong("reqid", job.getSearchParam().getRequisitionId());
			OrderRequisition req = (OrderRequisition) q.uniqueResult();
			if (req != null) {
				if (req.getComment() != null)
					req.getComment().getBytes();
				req.getStatus();
				if (req.getCreator() != null) {
					req.getCreator().getName();

				}
				if (req.getBaseOrganization() != null)
					req.getBaseOrganization().getName();
				for (OrderRequisitionLine rql : req.getOrderRequisitionLines()) {
					if (rql.getVendorOrderInformation() != null) {
						rql.getVendorOrderInformation().getId();
						if (rql.getVendorOrderInformation().getVendor() != null) {
							rql.getVendorOrderInformation().getVendor().getId();
							rql.getVendorOrderInformation().getVendor().getDescription();
							rql.getVendorOrderInformation().getVendorCatalog();
							rql.getVendorOrderInformation().getPricePerOrderingUnit();
							rql.getVendorOrderInformation().getUsageUnitPerOrderingUnit();
							if (rql.getVendorOrderInformation().getInventoryElement() != null) {
								if (rql.getVendorOrderInformation().getInventoryElement().getSupplyResourceItem() != null) {
									rql.getVendorOrderInformation().getInventoryElement().getSupplyResourceItem().getName();
								}
							}
							if (rql.getVendorOrderInformation().getManufacturer() != null) {
								rql.getVendorOrderInformation().getManufacturer().getDescription();

							}
							rql.getVendorOrderInformation().getComment();
							rql.getVendorOrderInformation().getVendorDescription();
							if (rql.getVendorOrderInformation().getManufacturerCatalog() != null) {
								rql.getVendorOrderInformation().getManufacturerCatalog().getBytes();
							}
						}

					}
					rql.getComment();
					rql.getQuantity();
					rql.getCreated().getDate();
					if (rql.getCreator() != null) {
						if (rql.getCreator().getPerson() != null) {
							rql.getCreator().getPerson().getDisplayName();
						}
					}

				}
			}
			result.setOrderRequisition(req);
			return result;

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			throw (e1);
		} finally {
			sm.closeSession();
		}

	}

	private InventoryJobResult getRequisitionLines(InventoryJob job) throws Exception {
		final String query = "select req from OrderRequisitionLine req where req.orderRequisition.id = :reqid";
		SessionManager sm = null;
		try {
			sm = SiteManager.Start();
			InventoryJobResult result = new InventoryJobResult();
			sm.openSession();
			Query q = sm.execute(query);
			q = q.setLong("reqid", job.getSearchParam().getRequisitionId());

			List<OrderRequisitionLine> res = q.list();
			for (OrderRequisitionLine rql : res) {
				if (rql.getVendorOrderInformation() != null) {
					rql.getVendorOrderInformation().getId();
					if (rql.getVendorOrderInformation().getVendor() != null) {
						rql.getVendorOrderInformation().getVendor().getId();
						rql.getVendorOrderInformation().getVendor().getDescription();
						rql.getVendorOrderInformation().getVendorCatalog();
						rql.getVendorOrderInformation().getPricePerOrderingUnit();
						rql.getVendorOrderInformation().getUsageUnitPerOrderingUnit();
						if (rql.getVendorOrderInformation().getInventoryElement() != null) {
							if (rql.getVendorOrderInformation().getInventoryElement().getSupplyResourceItem() != null) {
								rql.getVendorOrderInformation().getInventoryElement().getSupplyResourceItem().getName();
							}
						}
						if (rql.getVendorOrderInformation().getManufacturer() != null) {
							rql.getVendorOrderInformation().getManufacturer().getDescription();

						}
						rql.getVendorOrderInformation().getComment();
						rql.getVendorOrderInformation().getVendorDescription();
						if (rql.getVendorOrderInformation().getManufacturerCatalog() != null) {
							rql.getVendorOrderInformation().getManufacturerCatalog().getBytes();
						}
					}

				}
				rql.getComment();
				rql.getQuantity();
				rql.getCreated().getDate();
				if (rql.getCreator() != null) {
					if (rql.getCreator().getPerson() != null) {
						rql.getCreator().getPerson().getDisplayName();
					}
				}

			}
			result.setOrderReqLines(res);
			return result;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			throw (e1);
		} finally {
			sm.closeSession();
		}

	}

	private InventoryJobResult getOrderedItems(InventoryJob job) throws Exception {
		final String orderquery = "select line.purchaseOrder from PurchaseOrderLine line where line.inventoryElement.supplyResourceItem.id = :supply and line.statusWrapper.id in (0,1,2,5) and line.purchaseOrder.baseOrganization.id = :depid";
		final String requisitionqurey = "select line.orderRequisition from OrderRequisitionLine line where line.vendorOrderInformation.inventoryElement.supplyResourceItem.id = :supply and line.orderRequisition.statusWrapper.id in (0,1) and line.orderRequisition.baseOrganization = :depid";
		InventoryJobResult result = new InventoryJobResult();
		switch (job.getSearchParam().getKind()) {
		case SEARCH_ORDER: {
			SessionManager sm = SiteManager.Start();
			try {

				sm.openSession();
				Query q = sm.execute(orderquery);
				q = q.setLong("supply", job.getSearchParam().getSupplyResourceItemId());
				q.setLong("depid", job.getModuleDepartment().getId());

				List<PurchaseOrder> res = q.list();
				for (PurchaseOrder po : res) {
					po.getStatus();
				}
				result.setPurchaseOrders(res);

			} catch (Exception e) {
				throw (e);
			} finally {
				sm.closeSession();
			}
			break;
		}
		case SEARCH_REQUISITION: {
			SessionManager sm = SiteManager.Start();
			try {
				sm.openSession();
				Query q = sm.execute(requisitionqurey);
				q = q.setLong("supply", job.getSearchParam().getSupplyResourceItemId());
				q.setLong("depid", job.getModuleDepartment().getId());

				List<OrderRequisition> res = q.list();
				for (OrderRequisition rq : res) {
					rq.getStatus();
				}
				result.setRequisitions(res);

			} catch (Exception e) {
				throw (e);
			} finally {
				sm.closeSession();
			}
		}

		}
		/*
		 * case SessionManager sm = SiteManager.Start(); try {
		 * InventoryJobResult result = new InventoryJobResult();
		 * sm.openSession(); Query q = sm.execute(orderquery); q =
		 * q.setLong("supply", job.getSearchParam().getSupplyResourceItemId());
		 * q.setLong("depid", job.getModuleDepartment().getId());
		 * 
		 * List<PurchaseOrder> res = q.list(); for (PurchaseOrder po : res) {
		 * po.getStatus(); } result.setPurchaseOrders(res); return result; }
		 * catch (Exception e) { throw (e); } finally { sm.closeSession(); }
		 */
		return result;

	}

	static public InventoryJobResult processAdjustments(SessionManager sm, Department department, Collection<AdjustmentDescriptor> adjustments,
			ReceiveOrderParam reOrderParam) throws Exception {
		InventoryJobResult result = new InventoryJobResult();
		Map<AdjustmentDescriptor, List<TransactionLog>> adjustmentDescriptorTransactionLogMap = new HashMap<AdjustmentDescriptor, List<TransactionLog>>();

		if (adjustments != null && !adjustments.isEmpty()) {
			ReceiveOrderParam receiveOrderParam = reOrderParam;

			ReceiveOrder receiveOrder = null;
			if (receiveOrderParam != null) {
				receiveOrder = RADBeanFactory.getInstance().createBean(ReceiveOrder.class);
				if (receiveOrderParam.getReceiveOrderDate() != null) {
					receiveOrder.setReceivedDate(receiveOrderParam.getReceiveOrderDate());
				}
				receiveOrder.setComment(receiveOrderParam.getReceiveOrderComment());
				receiveOrder.setSalesTaxAmount(receiveOrderParam.getReceiveOrderSalesTaxAmount());
				receiveOrder.setShippingCost(receiveOrderParam.getReceiveOrderShippingCost());
				receiveOrder.setShippingNumber(receiveOrderParam.getReceiveOrderShippingNumber());
				receiveOrder.setPurchaseOrder(sm.get(PurchaseOrder.class, receiveOrderParam.getPurchaseOrderId()));
				receiveOrder.setLinkInfo(receiveOrderParam.getLinkInfo());
			}

			List<AdjustmentDescriptor> processedAdjustmentDescriptors = new ArrayList<AdjustmentDescriptor>();

			// SessionManager sessionManager = SiteManager.Start();
			sm.openSession();

			InventorySetupOptions options = InventorySetupManager.getInventorySetupOptionsByBusinessEntity(sm, department.getId());
			if (options != null) {
				try {
					for (AdjustmentDescriptor adjustmentDescriptor : adjustments) {
						sm.openTransaction();
						Adjustment adjustment = null;
						try {
							AdjustmentManager2 adjustmentManager = new AdjustmentManager2(sm, adjustmentDescriptor);
							// KKORNEL: AES-17699
							adjustmentManager.getInventorySetup();
							adjustmentManager.commit();
							adjustmentManager.print();
							adjustmentManager.save();
							adjustment = adjustmentDescriptor.getAdjustment();
							if (adjustmentManager.hasError()) {
								adjustmentDescriptorTransactionLogMap.put(adjustmentDescriptor, adjustmentManager.getTransactionLogs());
							} else if (adjustment != null || (adjustmentDescriptor.getKind() == SupplyUsageKind.CDM_USAGE_COUNT)) {
								processedAdjustmentDescriptors.add(adjustmentDescriptor);
							}

							if (adjustment != null && receiveOrder != null) {
								Long poLineId = (Long) adjustmentDescriptor.getTranzientProperty("PO_LINEID");
								if (poLineId != null) {
									ReceiveOrderLine receiveOrderLine = RADBeanFactory.getInstance().createBean(ReceiveOrderLine.class);

									receiveOrderLine.setPurchaseOrderLine(sm.get(PurchaseOrderLine.class, poLineId));
									receiveOrderLine.setReceiveOrder(receiveOrder);
									receiveOrderLine.setAdjustment(adjustment);

									sm.saveRAD(receiveOrderLine);
									sm.saveRAD(receiveOrder);
								}
							}

							sm.commitTransaction();
							sm.clear();
						} catch (OpenInventoryException openInventoryException) {
							sm.rollbackTransaction();
							log.error("Process adjustments", openInventoryException);
							result.setException(openInventoryException);
						} catch (Exception exception) {
							sm.rollbackTransaction();
							log.error("Process adjustments", exception);
							throw exception;
						}
					}

				} finally {
					sm.closeSession();
				}
			}
			result.setAdjustmentDescriptors(processedAdjustmentDescriptors);
			if (adjustmentDescriptorTransactionLogMap.size() > 0) {
				result.setException(new AdjustmentManagerException(adjustmentDescriptorTransactionLogMap));
			}
		}

		return result;

	}

	private InventoryJobResult processAdjustments(InventoryJob job) throws Exception {
		// InventoryJobResult result = new InventoryJobResult();
		// Map<AdjustmentDescriptor, List<TransactionLog>>
		// adjustmentDescriptorTransactionLogMap = new
		// HashMap<AdjustmentDescriptor, List<TransactionLog>>();
		//
		// if (job.getAdjustmentDescriptors() != null &&
		// !job.getAdjustmentDescriptors().isEmpty()) {
		// ReceiveOrderParam receiveOrderParam = job.getReceiveOrderParam();
		//
		// ReceiveOrder receiveOrder = null;
		// if (receiveOrderParam != null) {
		// receiveOrder =
		// RADBeanFactory.getInstance().createBean(ReceiveOrder.class);
		// receiveOrder.setComment(receiveOrderParam.getReceiveOrderComment());
		// receiveOrder.setSalesTaxAmount(receiveOrderParam.getReceiveOrderSalesTaxAmount());
		// receiveOrder.setShippingCost(receiveOrderParam.getReceiveOrderShippingCost());
		// receiveOrder.setShippingNumber(receiveOrderParam.getReceiveOrderShippingNumber());
		// receiveOrder.setPurchaseOrder(SiteManager.Start().get(PurchaseOrder.class,
		// receiveOrderParam.getPurchaseOrderId()));
		// receiveOrder.setLinkInfo(receiveOrderParam.getLinkInfo());
		// }
		//
		// List<AdjustmentDescriptor> processedAdjustmentDescriptors = new
		// ArrayList<AdjustmentDescriptor>();
		//
		// SessionManager sessionManager = SiteManager.Start();
		// sessionManager.openSession();
		//
		// InventorySetupOptions options =
		// InventorySetupManager.getInventorySetupOptionsByBusinessEntity(sessionManager,
		// job.getModuleDepartment()
		// .getId());
		// if (options != null) {
		// try {
		// for (AdjustmentDescriptor adjustmentDescriptor :
		// job.getAdjustmentDescriptors()) {
		// sessionManager.openTransaction();
		// Adjustment adjustment = null;
		// try {
		// AdjustmentManager2 adjustmentManager = new
		// AdjustmentManager2(sessionManager, adjustmentDescriptor);
		// adjustmentManager.commit();
		// adjustmentManager.print();
		// adjustmentManager.save();
		// adjustment = adjustmentDescriptor.getAdjustment();
		// if (adjustmentManager.hasError()) {
		// adjustmentDescriptorTransactionLogMap.put(adjustmentDescriptor,
		// adjustmentManager.getTransactionLogs());
		// } else if (adjustment != null || (adjustmentDescriptor.getKind() ==
		// SupplyUsageKind.CDM_USAGE_COUNT)) {
		// processedAdjustmentDescriptors.add(adjustmentDescriptor);
		// }
		//
		// if (adjustment != null && receiveOrder != null) {
		// Long poLineId = (Long)
		// adjustmentDescriptor.getTranzientProperty("PO_LINEID");
		// if (poLineId != null) {
		// ReceiveOrderLine receiveOrderLine =
		// RADBeanFactory.getInstance().createBean(ReceiveOrderLine.class);
		//
		// receiveOrderLine.setPurchaseOrderLine(sessionManager.get(PurchaseOrderLine.class,
		// poLineId));
		// receiveOrderLine.setReceiveOrder(receiveOrder);
		// receiveOrderLine.setAdjustment(adjustment);
		//
		// sessionManager.saveRAD(receiveOrderLine);
		// sessionManager.saveRAD(receiveOrder);
		// }
		// }
		//
		// sessionManager.commitTransaction();
		// sessionManager.clear();
		// } catch (OpenInventoryException openInventoryException) {
		// sessionManager.rollbackTransaction();
		// log.error("Process adjustments", openInventoryException);
		// result.setException(openInventoryException);
		// } catch (Exception exception) {
		// sessionManager.rollbackTransaction();
		// log.error("Process adjustments", exception);
		// throw exception;
		// }
		// }
		//
		// } finally {
		// sessionManager.closeSession();
		// }
		// }
		// result.setAdjustmentDescriptors(processedAdjustmentDescriptors);
		// if (adjustmentDescriptorTransactionLogMap.size() > 0) {
		// result.setException(new
		// AdjustmentManagerException(adjustmentDescriptorTransactionLogMap));
		// }
		// }
		//
		// return result;
		InventoryJobResult result = new InventoryJobResult();
		SessionManager sm = SiteManager.Start();

		result = processAdjustments(sm, job.getModuleDepartment(), job.getAdjustmentDescriptors(), job.getReceiveOrderParam());

		return result;
	}

	@SuppressWarnings("unchecked")
	private InventoryJobResult search(InventorySearchParam searchParam) throws Exception {
		InventoryJobResult result = new InventoryJobResult();

		SessionManager sm = SiteManager.Start();
		sm.openSession();
		try {
			if (searchParam != null && searchParam.getKind() != null) {
				switch (searchParam.getKind()) {
				case SERIAL_NUMBER_BY_INVENTORYELEMENT_EXPIRATIONDATE: {
					String queryString = "SELECT sn FROM SerialNumber as sn ";
					// #11709
					queryString += "LEFT JOIN FETCH sn.stock st ";
					// problem found at 2010.08.30 while test 14571
					// queryString +=
					// "WHERE (sn.stock.quantityOnHand = 1) AND (sn.stock.inventoryElement.id = :ieId) AND (sn.stock.expirationDate = :expDate)";
					// #15832 active only
					queryString += "WHERE (sn.active = 1) AND (sn.stock.quantityOnHand = 1) AND (sn.stock.inventoryElement.id = :ieId) AND (sn.stock.expirationDate = :expDate)";
					Query query = sm.execute(queryString);
					query.setParameter("ieId", searchParam.getInventoryElementId());
					query.setParameter("expDate", searchParam.getMinExpirationDate());
					List<SerialNumber> serialNumbers = query.list();
					result.setSerialNumbers(serialNumbers);
					break;
				}
				case EXPIRATIONDATE_BY_INVENTORYELEMENT_SERIALNUMBER: {
					String queryString = "SELECT st FROM stock as st ";
					queryString += "WHERE (st.serialNumber = :sn)";
					Query query = sm.execute(queryString);
					// #11709
					query.setParameter("sn", searchParam.getSerialNumberString());
					Stock stock = (Stock) query.uniqueResult();
					if (stock != null) {
						result.setExpirationDate(stock.getExpirationDate());
					}
					break;
				}
				case SERIAL_NUMBER_BY_INVENTORYELEMENT_ITEMLOCATION: {
					String queryString = "SELECT sn FROM SerialNumber as sn ";
					// #11709
					queryString += "LEFT JOIN FETCH sn.stock st ";
					// queryString +=
					// "WHERE (sn.active = :active) AND (sn.stock.inventoryElement.id = :ieId) and exists (SELECT sol.id FROM StockOnLocation sol WHERE (sol.stock.id = sn.stock.id) AND (sol.itemLocation.id = :ilId))";
					// problem found at 2010.08.30 while test 14571
					// queryString +=
					// "WHERE (sn.stock.quantityOnHand = 1) AND (sn.stock.inventoryElement.id = :ieId) and exists (SELECT sol.id FROM StockOnLocation sol WHERE (sol.stock.id = sn.stock.id) AND (sol.itemLocation.id = :ilId))";
					// #15832 active only
					queryString += "WHERE (sn.active = 1) AND (sn.stock.quantityOnHand = 1) AND (sn.stock.inventoryElement.id = :ieId) and exists (SELECT sol.id FROM StockOnLocation sol WHERE (sol.stock.id = sn.stock.id) AND (sol.itemLocation.id = :ilId))";
					Query query = sm.execute(queryString);
					query.setParameter("ieId", searchParam.getInventoryElementId());
					query.setParameter("ilId", searchParam.getItemLocationId());
					// query.setParameter("active", searchParam.getActive());
					List<SerialNumber> serialNumbers = query.list();
					result.setSerialNumbers(serialNumbers);
					break;
				}
				case SERIAL_NUMBER_BY_INVENTORYELEMENT: {
					String queryString = "SELECT sn FROM SerialNumber as sn ";
					// #11709
					queryString += "LEFT JOIN FETCH sn.stock st ";
					// queryString +=
					// "WHERE (sn.active = :active) AND (sn.stock.inventoryElement.id = :ieId)";
					// problem found at 2010.08.30 while test 14571
					// queryString +=
					// "WHERE (sn.stock.quantityOnHand = 1) AND (sn.stock.inventoryElement.id = :ieId) ";
					// #15832 active only
					queryString += "WHERE (sn.active = 1) AND (sn.stock.quantityOnHand = 1) AND (sn.stock.inventoryElement.id = :ieId) ";
					Query query = sm.execute(queryString);
					query.setParameter("ieId", searchParam.getInventoryElementId());
					// query.setParameter("active", searchParam.getActive());
					List<SerialNumber> serialNumbers = query.list();
					result.setSerialNumbers(serialNumbers);
					break;
				}
				case EXPIRATION_DATE_BY_INVENTORYELEMENT_ITEMLOCATION: {
					String queryString = "SELECT st FROM Stock as st ";
					queryString += "WHERE (st.inventoryElement.id = :ieId) and exists (SELECT sol.id FROM StockOnLocation sol WHERE (sol.stock.id = st.id) AND (sol.itemLocation.id = :ilId))";
					Query query = sm.execute(queryString);
					query.setParameter("ieId", searchParam.getInventoryElementId());
					query.setParameter("ilId", searchParam.getItemLocationId());
					// query.setParameter("active", searchParam.getActive());
					List<Stock> stocks = query.list();
					List<Date> expirationDates = new ArrayList<Date>();
					for (Stock stock : stocks) {
						if (stock.getExpirationDate() != null)
							expirationDates.add(stock.getExpirationDate());
					}
					result.setExpirationDates(expirationDates);
					break;
				}
				case CDM_USAGE_COUNT_FOR_SERIAL:
					if (searchParam.getSerialNumber() != null) {
						String query = "SELECT count(td) FROM TransactionDescriptor td WHERE td.adjustmentDescriptor.kindWrapper.id = "
								+ String.valueOf(SupplyUsageKind.CDM_USAGE_COUNT.ordinal()) + " AND td.serialNumber = :ser ";
						Object usagecount = sm.execute(query).setEntity("ser", searchParam.getSerialNumber()).uniqueResult();
						if (usagecount != null && usagecount instanceof Long) {
							result.setUsageCount(((Long) usagecount).intValue());
						}

					}
					break;
				case CDM_USAGE_COUNT_FOR_SERIAL_AFTER_SERVICE_DATE:
					if (searchParam.getSerialNumber() != null) {
						String swiQuery = "SELECT MAX(swi.id) FROM ServiceWarriantyInformation swi WHERE swi.serialNumber = :sn ";
						Long swiId = (Long) sm.execute(swiQuery).setEntity("sn", searchParam.getSerialNumber()).uniqueResult();

						if (swiId != null) {

							ServiceWarriantyInformation swi = sm.get(ServiceWarriantyInformation.class, swiId);
							if (swi.getLastServiceDate() != null) {
								String query = "SELECT count(td) FROM TransactionDescriptor td WHERE td.adjustmentDescriptor.kindWrapper.id = "
										+ String.valueOf(SupplyUsageKind.CDM_USAGE_COUNT.ordinal()) + " AND td.serialNumber = :ser "
										+ "AND td.adjustmentDescriptor.adjustmentDate > :addate";
								Object usagecount = sm.execute(query).setEntity("ser", searchParam.getSerialNumber()).setDate("addate",
										swi.getLastServiceDate()).uniqueResult();
								if (usagecount != null && usagecount instanceof Long) {
									result.setUsageCount(((Long) usagecount).intValue());
								}
							}
						}
					}
					break;
				case ADJUSTMENTS_FOR_HISTORY:
					if (searchParam.getInventoryElementId() != null) {
						List<InventoryElementHistoryInfo> historyInfos = AdjustmentHistoryHelper.getAdjustmentDescriptorPageForHistory(sm,
								searchParam);
						result.setHistoryInfos(historyInfos);
					}
					break;

				case ADJUSTMENT_DESCRIPTOR:
					getIsAdjustmentToItem(sm, result, searchParam);
					// AES-17613
					getEnableSupplyInitialization(sm, result, searchParam);
					if (!searchParam.withoutAdjustments) {
						List<AdjustmentDescriptor> adjustmentDescriptors = getDescriptors(sm, searchParam, result);
						result.setAdjustmentDescriptors(adjustmentDescriptors);
					}
					break;
				case ADJUSTMENT_DESCRIPTOR_FOR_SERIALS:
					// DP > AES-14571

					Set<AdjustmentDescriptor> ads = new HashSet<AdjustmentDescriptor>();
					List<SerialNumber> sns = sm.execute(
							"FROM SerialNumber sn WHERE sn.stock.inventoryElement.supplyResourceItem.id = :srid AND sn.stock.quantityOnHand = 1")
							.setLong("srid", searchParam.getSupplyResourceItemId()).list();
					getIsAdjustmentToItem(sm, result, searchParam);

					for (SerialNumber serialNumber : sns) {
						// KKORNEL: AES-14978
						TransactionDescriptor td = (TransactionDescriptor) sm
								.execute(
										"FROM TransactionDescriptor td WHERE ((td.serialNumber = :sn) or (td.serial = :snname )) and (td.adjustmentDescriptor.adjustment is not null) ORDER BY td DESC")
								.setEntity("sn", serialNumber).setString("snname", serialNumber.getSerial()).setMaxResults(1).uniqueResult();
						if (td != null && td.getSerialNumber().getStock().getQuantityOnHand() == 1) {

							ads.add(td.getAdjustmentDescriptor());
						}
					}

					for (AdjustmentDescriptor adjustmentDescriptor : ads) {
						if (adjustmentDescriptor.getInventoryElement() != null) {
							fetchItem(adjustmentDescriptor.getInventoryElement().getSupplyResourceItem());
						}
						if (adjustmentDescriptor.getAdjustmentOwner() != null) {
							adjustmentDescriptor.getAdjustmentOwner().getName();
						}
						if (adjustmentDescriptor.getAdjustment() != null) {
							adjustmentDescriptor.getAdjustment().getId();
						}
						fetchItem(adjustmentDescriptor.getTransactionCode());

						for (TransactionDescriptor transactionDescriptor : adjustmentDescriptor.getTransactionDescriptors()) {
							if (transactionDescriptor.getSerialNumber() != null) {
								fetchItem(transactionDescriptor.getSerialNumber().getRoom());
								for (ServiceWarriantyInformation serviceWarriantyInformation : transactionDescriptor.getSerialNumber()
										.getServiceWarriantyInformations()) {
									serviceWarriantyInformation.getExpirationDate();
								}
								for (ServiceHistory serviceHistory : transactionDescriptor.getSerialNumber().getServiceHistories()) {
									serviceHistory.getServiceDate();
								}
							}

							for (TransferDescriptor transferDescriptor : transactionDescriptor.getInv_fromDescriptor()) {
								transferDescriptor.getId();
							}

							for (TransferDescriptor transferDescriptor : transactionDescriptor.getInv_toDescriptors()) {
								transferDescriptor.getId();
							}

							fetchItem(transactionDescriptor.getSupplyResourceLocation());
							fetchItem(transactionDescriptor.getRoom());
						}
						for (TransferDescriptor transferDescriptor : adjustmentDescriptor.getTransferDescriptors()) {
							if (transferDescriptor.getFrom().getSerialNumber() != null) {

							}
							if (transferDescriptor.getTo().getSerialNumber() != null) {
								fetchItem(transferDescriptor.getTo().getSerialNumber().getRoom());
								for (ServiceWarriantyInformation serviceWarriantyInformation : transferDescriptor.getTo().getSerialNumber()
										.getServiceWarriantyInformations()) {
									serviceWarriantyInformation.getExpirationDate();
								}
								for (ServiceHistory serviceHistory : transferDescriptor.getTo().getSerialNumber().getServiceHistories()) {
									serviceHistory.getServiceDate();
								}
							}

							fetchItem(transferDescriptor.getTo().getSupplyResourceLocation());
							fetchItem(transferDescriptor.getTo().getRoom());
						}

						List<TransactionDescriptor> removeTds = new ArrayList<TransactionDescriptor>();
						if (searchParam.getKind().equals(InventorySearchKind.ADJUSTMENT_DESCRIPTOR_FOR_SERIALS)) {
							for (TransactionDescriptor td : adjustmentDescriptor.getTransactionDescriptors()) {
								if (td.getSerialNumber() != null && td.getSerialNumber().getStock() != null
										&& td.getSerialNumber().getStock().getQuantityOnHand() <= 0) {
									removeTds.add(td);
								}
							}
							adjustmentDescriptor.getTransactionDescriptors().removeAll(removeTds);
						}

					}
					searchParam.setSerialized(false);
					// AES-17613
					getEnableSupplyInitialization(sm, result, searchParam);
					getDescriptors(sm, searchParam, result);
					result.setAdjustmentDescriptors(new ArrayList(ads));
					break;

				case ITEM_LOCATION:
					List<ItemLocation> itemLocations = sm.execute(
							"FROM ItemLocation AS location WHERE location.location.baseOrganization.id = :department").setParameter("department",
							searchParam.getBaseOrganizationId()).list();
					for (ItemLocation itemLocation : itemLocations) {
						fetchItem(itemLocation.getLocation());
						fetchItem(itemLocation.getInventoryElement().getSupplyResourceItem());

						for (ItemLocation location : itemLocation.getInventoryElement().getItemLocations()) {
							fetchItem(location.getLocation());
						}
					}

					result.setItemLocations(itemLocations);
					break;

				case ITEM_LOCATION_REFERENCE_SEARCH: {
					int count = 0;
					ItemLocation itemLocation = sm.get(ItemLocation.class, searchParam.getItemLocationId());
					if (itemLocation != null) {
						Long locationCount = (Long) sm
								.execute(
										"SELECT count(td) FROM TransactionDescriptor td  WHERE td.adjustmentDescriptor.inventoryElement = :ie AND td.supplyResourceLocation = :srl")
								.setEntity("ie", itemLocation.getInventoryElement()).setEntity("srl", itemLocation.getLocation()).uniqueResult();
						if (locationCount != null) {
							count = locationCount.intValue();
						}
					}
					result.setLocationReferenceCount(count);
					break;
				}

				case VENDOR_ORDER_INFORMATION:
					List<VendorOrderInformation> vendorOrderInformations = new ArrayList<VendorOrderInformation>();
					if (searchParam.getSupplyResourceItemId() != null) {
						SupplyResourceItem supplyResourceItem = sm.get(SupplyResourceItem.class, searchParam.getSupplyResourceItemId());
						if (supplyResourceItem != null && supplyResourceItem.getInventoryElement() != null) {
							InventoryElement ie = OneToOneHelper.getInverseInstance(InventoryElement.class, supplyResourceItem.getInventoryElement());
							vendorOrderInformations.addAll(ie.getVendorOrderInformations());
						}
					} else {
						vendorOrderInformations = sm.execute("FROM VendorOrderInformation AS orderInfo").list();
					}
					for (VendorOrderInformation vendorOrderInformation : vendorOrderInformations) {
						if (vendorOrderInformation.getVendor() != null) {
							vendorOrderInformation.getVendor().getDescription();
						}
						if (vendorOrderInformation.getManufacturer() != null) {
							vendorOrderInformation.getManufacturer().getDescription();
						}
						if (vendorOrderInformation.getInventoryElement() != null) {
							if (vendorOrderInformation.getInventoryElement().getSupplyResourceItem() != null) {
								vendorOrderInformation.getInventoryElement().getSupplyResourceItem().getName();
							}
						}
						if (vendorOrderInformation.getOrderingUnit() != null) {
							vendorOrderInformation.getOrderingUnit().getName();
						}
						if (vendorOrderInformation.getInventoryElement() != null
								&& vendorOrderInformation.getInventoryElement().getSupplyResourceItem() != null) {
							vendorOrderInformation.getInventoryElement().getSupplyResourceItem().getName();

							for (ItemLocation location : vendorOrderInformation.getInventoryElement().getItemLocations()) {
								if (location.getLocation() != null) {
									location.getLocation().getName();
								}
							}
						}
					}
					result.setVendorOrderInformations(vendorOrderInformations);
					break;

				case SUPPLY_RESOURCE_ITEM:
					List<SupplyResourceItem> supplyResourceItems = InventorySearcher.searchSupplyResource(sm, searchParam);
					for (SupplyResourceItem supplyResourceItem : supplyResourceItems) {
						if (supplyResourceItem.getCategory() != null) {
							supplyResourceItem.getCategory().getName();
						}

						if (supplyResourceItem.getUsageUnit() != null) {
							supplyResourceItem.getUsageUnit().getName();
						}

						if (supplyResourceItem.getInventoryElement() != null) {
							InventoryElement ie = OneToOneHelper.getInverseInstance(InventoryElement.class, supplyResourceItem.getInventoryElement());
							String id = (ie.getId() != null ? ie.getId().toString() : "");
							for (ItemLocation itemLocation : ie.getItemLocations()) {
								SupplyResourceLocation supplyResourceLocation = itemLocation.getLocation();
								supplyResourceLocation.getName();

								supplyResourceLocation.putTranzientProperty(InventoryJobResult.SUPPLY_LOCATION_QOH + id, itemLocation
										.getQuantityOnHand());
								if (itemLocation.getDefaultLocation() != null && itemLocation.getDefaultLocation()) {
									supplyResourceLocation.putTranzientProperty(InventoryJobResult.SUPPLY_LOCATION_DEFAULT + id, Boolean.TRUE);
								}
							}
							InventoryElement ie_ = OneToOneHelper
									.getInverseInstance(InventoryElement.class, supplyResourceItem.getInventoryElement());
							for (VendorOrderInformation vendorOrderInformation : ie_.getVendorOrderInformations()) {
								if (vendorOrderInformation.getVendor() != null) {
									vendorOrderInformation.getVendor().getDescription();
								}
								if (vendorOrderInformation.getManufacturer() != null) {
									vendorOrderInformation.getManufacturer().getDescription();
								}
							}

							for (Stock stock : ie_.getStocks()) {
								for (StockOnLocation stockOnLocation : stock.getStockOnLocations()) {
									stockOnLocation.getItemLocation().getLocation().getName();
								}
							}
						}
					}
					result.setSupplyResourceItems(supplyResourceItems);
					break;

				case SUPPLY_RESOURCE_LOCATION:
					List<SupplyResourceLocation> supplyResourceLocations = InventorySearcher.searchSupplyResourceLocation(sm, searchParam);

					for (SupplyResourceLocation location : supplyResourceLocations) {
						fetchItem(location);
					}

					result.setSupplyResourceLocations(supplyResourceLocations);
					break;

				case EXPIRATION_DATE:
					List<Date> dates = InventorySearcher.searchExpirationDate(sm, searchParam);
					if (dates != null) {
						result.setDates(dates);
					}
					break;
				case EXPIRATION_DATE_COST:
					BigDecimal cost = InventorySearcher.searchExpirationDateUnitCost(sm, searchParam);
					if (cost != null) {
						result.setActualCost(cost);
					}
					break;

				case SERIAL_NUMBER:
					List<SerialNumber> serialNumbers = InventorySearcher.searchSerialNumber(sm, searchParam);
					if (serialNumbers != null) {
						for (SerialNumber serialNumber : serialNumbers) {
							if (serialNumber.getRoom() != null) {
								serialNumber.getRoom().getName();
							}
							for (ServiceWarriantyInformation swi : serialNumber.getServiceWarriantyInformations()) {
								swi.getExpirationDate();
							}
							for (ServiceHistory sh : serialNumber.getServiceHistories()) {
								sh.getComment();
							}
							if (serialNumber.getStock() != null) {
								serialNumber.getStock().getExpirationDate();
							}

							serialNumber.getSerial();
						}
						result.setSerialNumbers(serialNumbers);
					}
					break;

				case PURCHASE_ORDER:
					List<PurchaseOrder> purchaseOrders = InventorySearcher.searchPurchaseOrder(sm, searchParam);

					for (PurchaseOrder po : purchaseOrders) {
						po.getPoNumber();
					}

					result.setPurchaseOrders(purchaseOrders);
					break;

				case INVENTORY_ELEMENT:
					List<InventoryElement> inventoryElements = new ArrayList<InventoryElement>();

					Query query = null;
					if (searchParam.isExpiration()) {
						query = sm
								.execute("SELECT DISTINCT st.inventoryElement  FROM  Stock st WHERE st.expirationDate < :edate and st.quantityOnHand > 0 ");
						query.setParameter("edate", searchParam.getMaxExpirationDate());

					} else if (searchParam.getSupplyResourceItemId() != null) {
						query = sm
								.execute("FROM InventoryElement AS inventoryElement WHERE inventoryElement.supplyResourceItem.id = :supplyResource");
						query.setParameter("supplyResource", searchParam.getSupplyResourceItemId());
					} else {
						query = sm
								.execute("FROM InventoryElement AS inventoryElement WHERE inventoryElement.supplyResourceItem.baseOrganization.id = :baseOrganization AND inventoryElement.supplyResourceItem.active = :active");
						query.setParameter("baseOrganization", searchParam.getBaseOrganizationId());
						query.setParameter("active", searchParam.getActive() != null ? searchParam.getActive().booleanValue() : false);
					}

					if (query != null) {
						if (searchParam.getResultCount() > 0) {
							query.setMaxResults(searchParam.getResultCount());
						}
						inventoryElements.addAll(query.list());
					}

					for (InventoryElement inventoryElement : inventoryElements) {
						fetchItem(inventoryElement.getSupplyResourceItem());

						if (inventoryElement.getSupplyResourceItem() != null) {
							fetchItem(inventoryElement.getSupplyResourceItem().getCategory());
							fetchItem(inventoryElement.getSupplyResourceItem().getUsageUnit());
						}

						for (VendorOrderInformation vendorOrderInformation : inventoryElement.getVendorOrderInformations()) {
							vendorOrderInformation.getVendor().getDescription();
							vendorOrderInformation.getManufacturer().getDescription();
						}

						for (ItemLocation itemLocation : inventoryElement.getItemLocations()) {
							fetchItem(itemLocation.getLocation());
						}
					}
					result.setInventoryElements(inventoryElements);
					break;
				case SUPPLY_RESOURCE_ITEM_BY_ITEM_DEPARTMENT: {
					itemLocations = new ArrayList<ItemLocation>();
					Set<SupplyResourceLocation> srLocs = new HashSet<SupplyResourceLocation>();
					query = null;
					if (searchParam.getInventoryDepartment() != null) {
						String queryText = "SELECT il FROM ItemLocation il ";
						queryText += "LEFT JOIN FETCH il.inventoryElement ie ";
						queryText += "LEFT JOIN FETCH il.inventoryDepartment id ";
						queryText += "LEFT JOIN FETCH il.location srl ";
						queryText += "WHERE (id = :invDep) AND (ie.id = :ieId)";
						query = sm.execute(queryText);
						query.setParameter("invDep", searchParam.getInventoryDepartment());
						query.setParameter("ieId", searchParam.getInventoryElementId());
					}

					if (query != null) {
						itemLocations.addAll(query.list());
					}

					for (ItemLocation itemLocation : itemLocations) {
						if (itemLocation.getInventoryDepartment().equals(searchParam.getInventoryDepartment())) {
							srLocs.add(itemLocation.getLocation());
						}
					}
					result.setSupplyResourceLocations(new ArrayList<SupplyResourceLocation>(srLocs));
					// for (InventoryElement inventoryElement :
					// inventoryElements) {
					// fetchItem(inventoryElement.getSupplyResourceItem());
					// if (inventoryElement.getSupplyResourceItem() != null) {
					// fetchItem(inventoryElement.getSupplyResourceItem().getCategory());
					// fetchItem(inventoryElement.getSupplyResourceItem().getUsageUnit());
					// }
					//
					// for (ItemLocation itemLocation :
					// inventoryElement.getItemLocations()) {
					// if
					// (itemLocation.getInventoryDepartment().equals(searchParam.getInventoryDepartment()))
					// {
					// srLocs.add(itemLocation.getLocation());
					// }
					// fetchItem(itemLocation.getLocation());
					// }
					// }
					break;
				}
				case CARRIER_CODES:
					Long resourceId = searchParam.getSupplyResourceItemId();
					if (resourceId != null) {
						List<CarrierCodes> list = sm.execute(
								"select c from CarrierCodes as c " + "left join fetch c.additionalReveneuCode " + "left join fetch c.cptCode "
										+ "left join fetch c.cptModifier1 " + "left join fetch c.cptModifier2 " + "left join fetch c.cptModifier3 "
										+ "left join fetch c.cptModifier4 " + "left join fetch c.insuranceCarrier "
										+ "left join fetch c.revenueCode " + "where c.supplyResourceItem.id=" + resourceId).list();
						result.setCarrierCodes(list);
					}
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// #17896
			// throw e;
			result.setException(e);
		} finally {
			sm.closeSession();
		}

		return result;
	}

	private InventoryJobResult uploadInventorySetup(InventorySetupOptions option) throws Exception {
		InventoryJobResult result = new InventoryJobResult();

		SessionManager sm = SiteManager.Start();
		sm.openSession();

		try {
			Query query = sm.execute("FROM InventorySetupOptions AS option WHERE option.baseOrganization.id = :baseOrganization");
			query.setParameter("baseOrganization", option.getBaseOrganization().getId());

			InventorySetupOptions savedOption = (InventorySetupOptions) query.uniqueResult();
			if (savedOption == null || (option != null && option.getId() != null && savedOption.getId().equals(option.getId()))) {
				sm.openTransaction();
				try {
					sm.clear();
					sm.saveRAD(option.getPurchaseOrderCreationCalculation());
					sm.saveRAD(option);
					sm.commitTransaction();

					option = sm.get(InventorySetupOptions.class, option.getId());
					fetchInventorySetupOptions(option);
					result.setInventorySetupOptions(option);
				} catch (Exception exception) {
					sm.rollbackTransaction();
					log.error("Upload Inventory Setup", exception);
				}
			}
			if (result.getInventorySetupOptions() == null) {
				fetchInventorySetupOptions(option);
				result.setInventorySetupOptions(savedOption);
			}
		} finally {
			sm.closeSession();
		}
		return result;
	}

	private InventoryJobResult uploadSupplyResourceItem(InventoryJob job) throws Exception {
		InventoryJobResult result = new InventoryJobResult();
		Map<AdjustmentDescriptor, List<TransactionLog>> adjustmentDescriptorTransactionLogMap = new HashMap<AdjustmentDescriptor, List<TransactionLog>>();
		if (job.getSupplyResourceItem() != null) {
			SessionManager sm = SiteManager.Start();
			sm.openSession();
			try {
				sm.openTransaction();
				try {
					if (job.getSupplyResourceItem().getWasteCode() != null && job.getSupplyResourceItem().getWasteCode().isUndefined()) {
						job.getSupplyResourceItem().setWasteCode(null);
					}
					if (job.getSupplyResourceItem().getCptCode() != null && job.getSupplyResourceItem().getCptCode().isUndefined()) {
						job.getSupplyResourceItem().setCptCode(null);
					}

					SharedDictionaryManager sdm = new SharedDictionaryManager(sm);
					// KKORNEL: AES-12394
					boolean isNew = (job.getSupplyResourceItem() != null) && (job.getSupplyResourceItem().getChangedKind() == ChangedKind.CREATED);

					// AES-15473
					if (job.getSupplyResourceItem().getBilledBy() == null)
						job.getSupplyResourceItem().setBilledBy(BilledByType.NONE);

					sdm.saveItem(job.getSupplyResourceItem());

					DictionarySchedulingResourceManager.executeSchedulingResourceUpdate(job.getSupplyResourceItem(), sm);

					if (job.getAdjustmentDescriptors() != null) {
						for (AdjustmentDescriptor adjustmentDescriptor : job.getAdjustmentDescriptors()) {
							if (adjustmentDescriptor.getTransactionCode() != null) {
								adjustmentDescriptor.getInventoryElement().setSupplyResourceItem(job.getSupplyResourceItem());
								InventoryElement ie = OneToOneHelper.getInverseInstance(InventoryElement.class, job.getSupplyResourceItem()
										.getInventoryElement());
								adjustmentDescriptor.setInventoryElement(ie);

								AdjustmentManager2 adjustmentManager = new AdjustmentManager2(sm, adjustmentDescriptor);
								adjustmentManager.commit();
								adjustmentManager.print();
								adjustmentManager.save();
								if (adjustmentManager.hasError()) {
									adjustmentDescriptorTransactionLogMap.put(adjustmentDescriptor, adjustmentManager.getTransactionLogs());
								}

								// for (TransactionDescriptor td :
								// adjustmentDescriptor.getTransactionDescriptors()){
								// if (td.getSerialNumber() != null){
								// for (ServiceHistory sh :
								// td.getSerialNumber().getServiceHistories()){
								// sm.saveRAD(sh);
								// }
								// for (ServiceWarriantyInformation swi :
								// td.getSerialNumber().getServiceWarriantyInformations()){
								// sm.saveRAD(swi);
								// }
								// }
								// }
							}
						}
					}

					// AES-7472
					if (job.getCarrierCodes() != null) {
						HashSet<CarrierCodes> carrierCodes = new HashSet<CarrierCodes>(job.getCarrierCodes());
						for (CarrierCodes code : job.getSupplyResourceItem().getCarrierCodeses()) {
							if (!carrierCodes.contains(code)) {
								sm.delete(code);
							}
						}
						for (CarrierCodes code : carrierCodes) {
							CarrierCodes oldCode = (code.getId() == null ? null : sm.get(CarrierCodes.class, code.getId()));
							if (oldCode != null) {
								if (code.getChangedKind() == ChangedKind.DELETED) {
									sm.delete(oldCode);
									continue;
								}
								List<Object> props = code.getIndexedProperties();
								oldCode.setIndexedProperties(props.toArray());
								code = oldCode;
							}
							code.setSupplyResourceItem(job.getSupplyResourceItem());
							sm.saveOrUpdate(code);
						}
					}
					// KKORNEL: AES-11414 - Insert a line for supply resource
					// for contracts
					// KKORNEL: AES-12394
					ServerContractManager.insertSupplyResource(sm, job.getSupplyResourceItem(), isNew);
					sm.commitTransaction();

					result.setSupplyResourceItems(Arrays.asList(job.getSupplyResourceItem()));
				} catch (Exception exception) {
					sm.rollbackTransaction();
					log.error("Upload Supply/Resource Item", exception);
					throw exception;
				}
			} finally {
				sm.closeSession();
			}
		}
		if (adjustmentDescriptorTransactionLogMap.size() > 0) {
			result.setException(new AdjustmentManagerException(adjustmentDescriptorTransactionLogMap));
		}
		return result;
	}

	private InventoryJobResult uploadItemLocation(InventoryJob job) throws Exception {
		InventoryJobResult result = new InventoryJobResult();
		List<ItemLocation> itl = new ArrayList<ItemLocation>();
		if (job.getLocation() != null) {
			SessionManager sm = SiteManager.Start();
			sm.openSession();
			try {
				sm.openTransaction();
				try {
					sm.saveRAD(job.getLocation());
					sm.commitTransaction();
					itl.add(sm.get(ItemLocation.class, job.getLocation().getId()));
					result.setItemLocations(itl);
				} catch (Exception exception) {
					sm.rollbackTransaction();
					log.error("Upload ItemLocation", exception);
					throw exception;
				}
			} finally {
				sm.closeSession();
			}

		}

		return result;
	}

	@SuppressWarnings("unchecked")
	private InventoryJobResult getAdjustmentHistoryInfo(InventoryJob job) throws Exception {
		InventoryJobResult result = new InventoryJobResult();
		result.setHistoryInfos(new ArrayList<InventoryElementHistoryInfo>());

		// Adjustment Common Info
		AdjustmentHistoryInfo adji = new AdjustmentHistoryInfo();

		SessionManager sm = SiteManager.Start();
		sm.openSession();
		try {

			Query query = sm.execute("FROM AdjustmentDescriptor ad  WHERE ad.id = :id");
			query.setParameter("id", job.getId());
			AdjustmentDescriptor ad = (AdjustmentDescriptor) query.uniqueResult();

			// Load Adjustment common info
			loadAdjustmentCommonInfo(sm, ad, adji);

			// Load transactions info (price , qty , etc..)
			if (ad.getAdjustment() != null) {

				if (!ad.getTransactionCode().getCalculationEffect().equals(TransactionCalculationEffect.TRANSFER)) {
					List<StockAdjustment> stockAdjustments = (List<StockAdjustment>) sm.execute(
							"FROM StockAdjustment sta WHERE sta.adjustment = :ad ").setEntity("ad", ad.getAdjustment()).list();
					if (stockAdjustments != null) {
						for (StockAdjustment sta : stockAdjustments) {

							for (StockOnLocationAdjustment stola : sta.getStockOnLocationAdjustments()) {
								InventoryElementHistoryInfo iehi = new InventoryElementHistoryInfo();
								iehi.location = stola.getStockOnLocation().getItemLocation().getLocation().getName();
								loadInventoryElementHistoryByTransaction(sm, sta, ad, iehi);
								result.getHistoryInfos().add(iehi);
							}

						}
					} else {
						for (TransactionDescriptor td : ad.getTransactionDescriptors()) {
							InventoryElementHistoryInfo iehi = new InventoryElementHistoryInfo();
							loadInventoryElementHistoryByAdjustmentDescriptor(sm, td, iehi);
							result.getHistoryInfos().add(iehi);
						}
					}
				} else {

					loadInventoryElementHistoryByTransfer(sm, ad, result);

				}

			} else {
				for (TransactionDescriptor td : ad.getTransactionDescriptors()) {
					InventoryElementHistoryInfo iehi = new InventoryElementHistoryInfo();
					loadInventoryElementHistoryByAdjustmentDescriptor(sm, td, iehi);
					result.getHistoryInfos().add(iehi);
				}

			}
		} finally {
			result.setAdjustmentHistoryInfo(adji);
			sm.closeSession();
		}

		return result;
	}

	private void loadInventoryElementHistoryByAdjustmentDescriptor(SessionManager sm, TransactionDescriptor td, InventoryElementHistoryInfo iehi) {

		// Vendor name
		if (td.getVendorOrderInformation() != null) {
			iehi.vendorName = td.getVendorOrderInformation().getVendor().getDescription();
		}
		// Serialnumber
		if (td.getSerial() != null) {
			iehi.serial = td.getSerial();
		} else if (td.getSerialNumber() != null) {
			iehi.serial = td.getSerialNumber().getSerial();
		}

		// ExpirationDate
		if (td.getExpirationDate() != null) {
			iehi.expiration = td.getExpirationDate();
		}

		// Quantity
		iehi.qty = String.valueOf(Math.abs(td.getQuantity()));
		// UnitPrice
		iehi.unitPrice = td.getUnitCost();

		// Acct, Patient name , Case name
		if (td.getAdjustmentDescriptor().getSupplyLog() != null && td.getAdjustmentDescriptor().getSupplyLog().getCdmCaseHistory() != null
				&& td.getAdjustmentDescriptor().getSupplyLog().getCdmCaseHistory().getPatient() != null
				&& td.getAdjustmentDescriptor().getSupplyLog().getCdmCaseHistory().getPatient().getAccount() != null) {
			iehi.acct = td.getAdjustmentDescriptor().getSupplyLog().getCdmCaseHistory().getPatient().getAccount().getAccountNumber();
			iehi.caseName = td.getAdjustmentDescriptor().getSupplyLog().getCdmCaseHistory().getPmCase().getName();
			iehi.patientName = td.getAdjustmentDescriptor().getSupplyLog().getCdmCaseHistory().getPatient().getPerson().getDisplayName();
		}
	}

	private void loadAdjustmentCommonInfo(SessionManager sm, AdjustmentDescriptor ad, AdjustmentHistoryInfo adji) {
		Query query;
		if (ad.getAdjustment() != null) {
			adji.setPostDate(ad.getAdjustment().getDate());

			query = sm.execute("select ro.receiveOrder.purchaseOrder from ReceiveOrderLine ro where ro.adjustment.id = :id");
			query.setParameter("id", ad.getAdjustment().getId());
			PurchaseOrder pres = (PurchaseOrder) query.uniqueResult();
			if (pres != null) {
				if (pres.getPrefix() != null && pres.getPrefix() != "") {
					adji.setPoNum(pres.getPrefix() + "-" + String.valueOf(pres.getPoNumber()));
				} else
					adji.setPoNum(String.valueOf(pres.getPoNumber()));

			}
		}
		if (ad.getAdjustmentOwner() != null)
			adji.setUsername(ad.getAdjustmentOwner().getName());

		if (ad.getComment() != null)
			adji.setComment(ad.getComment());

	}

	private void loadInventoryElementHistoryByTransaction(SessionManager sm, StockAdjustment sta, AdjustmentDescriptor ad,
			InventoryElementHistoryInfo iehi) {

		// Vendor name
		if (sta.getStock().getVendorOrderInformation() != null) {
			iehi.vendorName = sta.getStock().getVendorOrderInformation().getVendor().getDescription();
		}
		// Serialnumber
		if (sta.getStock().getInventoryElement().getSupplyResourceItem().isSerialized()) {
			String sn = (String) sm.execute("SELECT sn.serial FROM SerialNumber sn WHERE sn.stock = :st").setEntity("st", sta.getStock())
					.uniqueResult();
			iehi.serial = sn;
		}
		// ExpirationDate
		if (sta.getStock().getInventoryElement().getSupplyResourceItem().isExpiration()) {
			iehi.expiration = sta.getStock().getExpirationDate();
		}

		// Quantity
		iehi.qty = String.valueOf(Math.abs(sta.getQuantity()));
		// UnitPrice
		iehi.unitPrice = sta.getStock().getUnitCost();

		// Acct, Patient name , Case name
		if (ad.getSupplyLog() != null && ad.getSupplyLog().getCdmCaseHistory() != null && ad.getSupplyLog().getCdmCaseHistory().getPatient() != null
				&& ad.getSupplyLog().getCdmCaseHistory().getPatient().getAccount() != null) {
			iehi.acct = ad.getSupplyLog().getCdmCaseHistory().getPatient().getAccount().getAccountNumber();
			iehi.caseName = ad.getSupplyLog().getCdmCaseHistory().getPmCase().getName();
			iehi.patientName = ad.getSupplyLog().getCdmCaseHistory().getPatient().getPerson().getDisplayName();
		}

	}

	private void loadInventoryElementHistoryByTransfer(SessionManager sm, AdjustmentDescriptor ad, InventoryJobResult result) {

		// Vendor name
		List<TransferDescriptor> transferDescriptors = (List<TransferDescriptor>) sm.execute(
				"SELECT trd FROM TransferDescriptor trd WHERE trd.adjustmentDescriptor = :ad ").setEntity("ad", ad).list();

		for (TransferDescriptor trd : transferDescriptors) {
			
			InventoryElementHistoryInfo iehi = new InventoryElementHistoryInfo();

			if (trd != null && trd.getFrom() != null) {
				loadInventoryElementHistoryByTransactionDescriptor(sm, trd.getFrom(), iehi);

				if (trd.getFrom().getSupplyResourceLocation() != null) {
					iehi.from = trd.getFrom().getSupplyResourceLocation().getName();
				}
				if (trd.getTo().getSupplyResourceLocation() != null) {
					iehi.to = trd.getTo().getSupplyResourceLocation().getName();
				}
			} else {
				for (TransactionDescriptor td : ad.getTransactionDescriptors()) {
					loadInventoryElementHistoryByTransactionDescriptor(sm, td, iehi);
					if (td.getSupplyResourceLocation() != null) {
						iehi.from = td.getSupplyResourceLocation().getName();
					}
				}
			}
			// Quantity
			// UnitPrice

			// Acct, Patient name , Case name
			if (ad.getSupplyLog() != null && ad.getSupplyLog().getCdmCaseHistory() != null
					&& ad.getSupplyLog().getCdmCaseHistory().getPatient() != null
					&& ad.getSupplyLog().getCdmCaseHistory().getPatient().getAccount() != null) {
				iehi.acct = ad.getSupplyLog().getCdmCaseHistory().getPatient().getAccount().getAccountNumber();
				iehi.caseName = ad.getSupplyLog().getCdmCaseHistory().getPmCase().getName();
				iehi.patientName = ad.getSupplyLog().getCdmCaseHistory().getPatient().getPerson().getDisplayName();
			}
			result.getHistoryInfos().add(iehi);
		}

	}

	private void loadInventoryElementHistoryByTransactionDescriptor(SessionManager sm, TransactionDescriptor td, InventoryElementHistoryInfo iehi) {
		if (td.getVendorOrderInformation() != null) {
			iehi.vendorName = td.getVendorOrderInformation().getVendor().getDescription();
		}
		// Serialnumber
		if (td.getSerialNumber() != null) {
			iehi.serial = td.getSerialNumber().getSerial();
		}
		// ExpirationDate
		if (td.getExpirationDate() != null) {
			iehi.expiration = td.getExpirationDate();
		}
		iehi.qty = String.valueOf(Math.abs(td.getQuantity()));
		iehi.unitPrice = td.getUnitCost();

	}

	// DP > http://jira.amkai.com:8080/browse/AES-15645
	protected List<AdjustmentDescriptor> getDescriptors(SessionManager sm, InventorySearchParam searchParam, InventoryJobResult result)
			throws Exception {

		List<AdjustmentDescriptor> adjustmentDescriptors = InventorySearcher.searchAdjustmentDescriptors(sm, searchParam);
		for (AdjustmentDescriptor adjustmentDescriptor : adjustmentDescriptors) {
			if (adjustmentDescriptor.getInventoryElement() != null) {
				fetchItem(adjustmentDescriptor.getInventoryElement().getSupplyResourceItem());
			}
			if (adjustmentDescriptor.getAdjustmentOwner() != null) {
				adjustmentDescriptor.getAdjustmentOwner().getName();
			}
			if (adjustmentDescriptor.getAdjustment() != null) {
				adjustmentDescriptor.getAdjustment().getId();
			}
			fetchItem(adjustmentDescriptor.getTransactionCode());

			for (TransactionDescriptor transactionDescriptor : adjustmentDescriptor.getTransactionDescriptors()) {
				if (transactionDescriptor.getSerialNumber() != null) {
					fetchItem(transactionDescriptor.getSerialNumber().getRoom());
					for (ServiceWarriantyInformation serviceWarriantyInformation : transactionDescriptor.getSerialNumber()
							.getServiceWarriantyInformations()) {
						serviceWarriantyInformation.getExpirationDate();
					}
					for (ServiceHistory serviceHistory : transactionDescriptor.getSerialNumber().getServiceHistories()) {
						serviceHistory.getServiceDate();
					}
				}

				for (TransferDescriptor transferDescriptor : transactionDescriptor.getInv_fromDescriptor()) {
					transferDescriptor.getId();
				}

				for (TransferDescriptor transferDescriptor : transactionDescriptor.getInv_toDescriptors()) {
					transferDescriptor.getId();
				}

				fetchItem(transactionDescriptor.getSupplyResourceLocation());
				fetchItem(transactionDescriptor.getRoom());
			}

		}
		return adjustmentDescriptors;

	}

	private boolean hasAdjustementDescriptor(SessionManager sm, InventorySearchParam searchParam, String otherConditions) {
		boolean result = false;
		String query = "SELECT ad.id FROM AdjustmentDescriptor ad WHERE ad.inventoryElement";
		Long id = null;
		if (searchParam.getSupplyResourceItemId() != null) {
			query += ".supplyResourceItem.id = :id";
			id = searchParam.getSupplyResourceItemId();
		} else if (searchParam.getInventoryElementId() != null) {
			query += ".id = :id";
			id = searchParam.getInventoryElementId();
		}
		if (otherConditions != null)
			query += otherConditions;
		if (id != null) {
			List list = sm.execute(query).setLong("id", id).setMaxResults(1).list();
			if (list != null && !list.isEmpty()) {
				result = true;
			}
		}
		return result;
	}

	private void getIsAdjustmentToItem(SessionManager sm, InventoryJobResult result, InventorySearchParam searchParam) {
		// AES-17613
		boolean hasAdjustment = hasAdjustementDescriptor(sm, searchParam, null);
		result.setIsAdjustmentToItem(hasAdjustment);
	}

	private void getEnableSupplyInitialization(SessionManager sm, InventoryJobResult result, InventorySearchParam searchParam) {
		// AES-17613
		boolean hasNonInitializationAdjustment = hasAdjustementDescriptor(sm, searchParam, " and not (ad.kindWrapper.id in ("
				+ SupplyUsageKind.SR_INVENTORY_START_ADD.ordinal() + ", " + SupplyUsageKind.SR_INVENTORY_START_SUB.ordinal() + "))");
		result.setEnableSupplyInitialization(!hasNonInitializationAdjustment);
	}

}
